#include "uwidget.h"
#include "uapplication.h"
#include "style/upalette.h"
#include "style/uproxystyle.h"

#include <QPainter>
#include <QPainterPath>

UWidget::UWidget(QWidget* parent) : QWidget(parent)
{
    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}

void UWidget::addDropShadowEffect(bool isOpen)
{
    if (m_isOpen != isOpen)
    {
        m_isOpen = isOpen;
        update();
    }
}

int UWidget::margins() const
{
    return m_margins;
}

void UWidget::setMargins(int margins)
{
    if (m_margins != margins)
    {
        m_margins = margins;
        update();
    }
}

void UWidget::setRadius(int radius)
{
    if (m_radius != radius)
    {
        m_radius = radius;
        update();
    }
}

void UWidget::setBackgroundColor(const QBrush &brush)
{
    auto palette = this->palette();
    palette.setBrush(backgroundRole(), brush);
    setPalette(palette);
}

void UWidget::setBackground(int role)
{
    if (m_role != role)
    {
        m_role = role;
        update();
    }
}

void UWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QColor backgroundColor = (m_role >= 0) ? uApp->applicationPalette()->color(m_role) : palette().color(backgroundRole());

    QPainterPath path;
    path.addRoundedRect(rect(), m_radius, m_radius);
    painter.setClipPath(path);

    QRect rect = QRect(m_margins, m_margins, width() - m_margins * 2, height() - m_margins * 2);
    if (m_isOpen && m_margins > 0)
    {
        UProxyStyle::drawDropShadow(painter, this->rect(), m_margins, m_radius, uApp->applicationPalette()->color(QPalette::Shadow));
    }

    QPainterPath rectPath;
    rectPath.addRoundedRect(rect, m_radius, m_radius);
    painter.fillPath(rectPath, backgroundColor);
}
